/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/user/{userId}")
@Component
@Slf4j
public class WebSocketServer {
    /**
     * Store all connected sessions quantities
     */
    private static int onlineCount = 0;
    /**
     * Store all connected sessions
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * The connection session
     */
    private Session session;
    /**
     * The connection session user id
     */
    private String userId = "";

    /**
     * Called after an opening handshake has been performed and the given websocket is ready to be written on.
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;

        if (!webSocketMap.containsKey(userId)) {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }

        log.info("user connect:{},current user count:{}", userId, getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("user:{},net error!!!!!!", userId);
        }
    }

    /**
     * Called after the websocket connection has been closed
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        log.info("user out:{},current user count:{}", userId, getOnlineCount());
    }

    /**
     * Callback for string messages received from the client
     *
     * @param message client message
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket message】receive a message from the client:{}", message);
    }

    /**
     * Called when the session protocol error occurs.
     *
     * @param session The session.
     * @param error   The exception.
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("user error:" + this.userId + ",cause:" + error.getMessage(), error);
    }

    /**
     * server send message to client
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * server send message to special client
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        log.info("send:" + userId + "，message:" + message);
        if (StringUtils.hasText(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("user" + userId + ",offline！");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
